package com.inifitness.admin.core.security.model;

import java.util.Collection;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;

import com.inifitness.admin.core.system.model.dto.UserAuthInfo;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

/**
 * 系统用户服务类
 *
 * @author sunjinfeng
 * @version 1.0.0
 * @since 2024/04/18 11:00:00
 */
@Data
@NoArgsConstructor
public class SysUserDetails implements UserDetails {

  @Getter
  private Long userId;

  private String username;

  private String password;

  private Boolean enabled;

  private Collection<SimpleGrantedAuthority> authorities;

  private Set<String> perms;

  private Long deptId;

  private Integer dataScope;

  public SysUserDetails(UserAuthInfo user) {
    this.userId = user.getUserId();
    Set<String> roles = user.getRoles();
    Set<SimpleGrantedAuthority> authoritySet;
    if (CollUtil.isNotEmpty(roles)) {
      authoritySet = roles.stream()
          // 标识角色
          .map(role -> new SimpleGrantedAuthority("ROLE_" + role))
          .collect(Collectors.toSet());
    } else {
      authoritySet = Collections.emptySet();
    }
    this.authorities = authoritySet;
    this.username = user.getUsername();
    this.password = user.getPassword();
    this.enabled = ObjectUtil.equal(user.getStatus(), 1);
    this.perms = user.getPerms();
    this.deptId = user.getDeptId();
    this.dataScope = user.getDataScope();
  }


  @Override
  public Collection<? extends GrantedAuthority> getAuthorities() {
    return this.authorities;
  }

  @Override
  public String getPassword() {
    return this.password;
  }

  @Override
  public String getUsername() {
    return this.username;
  }

  @Override
  public boolean isAccountNonExpired() {
    return true;
  }

  @Override
  public boolean isAccountNonLocked() {
    return true;
  }

  @Override
  public boolean isCredentialsNonExpired() {
    return true;
  }

  @Override
  public boolean isEnabled() {
    return this.enabled;
  }

}
